﻿using AutoMapper;
using MediatR;
using SmartCity.ProcessEngine.Api.Write.Application.Command.Node;
using SmartCity.ProcessEngine.Domain.Entities;
using SmartCity.ProcessEngine.ErrorCode;
using SmartCity.ProcessEngine.Infrastructure.Interface;
using Yitter.IdGenerator;

namespace SmartCity.ProcessEngine.Api.Write.Application.CommandHandler.Node
{
    public class CreateNodeHander : IRequestHandler<CreateNodeCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<NodeModel> nodeRepo;
        private readonly IMapper mapper;
        private readonly ILogger<CreateNodeHander> logger;

        /// <summary>
        /// 通过构造函数注入,
        /// </summary>
        /// <param name="nodeRepo"></param>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        public CreateNodeHander(IBaseRepository<NodeModel> nodeRepo,IMapper mapper  ,ILogger<CreateNodeHander> logger)
        {
            this.nodeRepo = nodeRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(CreateNodeCommand request, CancellationToken cancellationToken)
        {
            var model = mapper.Map<NodeModel>(request);
            model.Id = YitIdHelper.NextId();

            //1.先查询数据条数(含已逻辑删除的)+1
            var count = nodeRepo.GetAll().Count() + 1;

            //拼接填充为指定格式的数据
            model.NodeCode = "N" + count.ToString().PadLeft(4,'0');       // "N0001";??怎么构建编号格式的数据

            var r = await nodeRepo.CreateAsync(model);
            if (r > 0)
            {
                logger.LogInformation("添加节点成功:"+request.NodeName);
                return new ApiResult<int>().Success("添加节点成功", r); 
            }
            else {
                logger.LogError("添加节点失败:"+request.NodeName);
                return new ApiResult<int>().AddFail("节点");
            }
             
        }
    }
}
